#!/usr/bin/python
# -*- coding: utf-8 -*-

import psycopg2
import sys
import json
import cgi
import datetime
import db_conf
con = None
try:
    qform = cgi.FieldStorage()
    compound_id = qform.getvalue('compound_id')
    precursor_id = qform.getvalue('precursor_compound_id')
    reagent_id = qform.getvalue('derivatization_reagent_id')
    formula = qform.getvalue('product_formula')
    config = db_conf.getConfig('metabvis.conf')
    con = psycopg2.connect(host=db_conf.getDBHost(config), database=db_conf.getDBName(config), port=db_conf.getDBPort(config), user=db_conf.getUser(config), password=db_conf.getPassword(config))
    cur = con.cursor()
    if (precursor_id != None and len(precursor_id) > 0):	
        insert_precursor = 'insert into compound_derivatization values (%s, %s, %s)' %(precursor_id, compound_id, reagent_id)
        cur.execute(insert_precursor)    
        cur.execute("commit")      
    if (formula != None):
        #update compound set sum_formula = 'CH3' where compound_id = 304;
        cur.execute("""update compound set sum_formula=%s where compound_id = %s""", (formula, compound_id))
        cur.execute("commit")	
        
    #rows = cur.fetchall()
    print "Content-type: text/html;charset=utf-8\r\n"
    pa = {}
    pa['_status'] = "200"
    print json.dumps(pa)
except psycopg2.DatabaseError, e:
    print 'Error %s' % e    
    sys.exit(1)    
finally:
    if con:
        con.close()
